/**
 * 导出服务
 * 处理组件的导出相关逻辑
 */

import { loadComponentExport } from './componentLoader';

export class ExportService {
  /**
   * 处理单个组件导出
   * @param {Object} component 组件数据
   * @param {Object} options 导出选项
   * @returns {Promise<Object>} 导出结果
   */
  async exportComponent(component, options = {}) {
    try {
      // 动态加载组件的导出处理模块
      const exportHandler = await loadComponentExport(component.type);
      
      if (exportHandler) {
        // 使用组件特定导出逻辑
        return {
          html: exportHandler.generateHTML(component, options),
          js: exportHandler.generateJS ? exportHandler.generateJS(component, options) : '',
          resources: exportHandler.resources || []
        };
      }
      
      // 默认导出处理
      return this.defaultExporter(component, options);
    } catch (error) {
      console.error(`[ExportService] 导出处理错误 (${component.type}):`, error);
      return this.defaultExporter(component, options);
    }
  }
  
  /**
   * 默认导出处理器
   * @param {Object} component 组件数据
   * @param {Object} options 导出选项
   * @returns {Object} 导出结果
   */
  defaultExporter(component, options = {}) {
    const { id, style = {}, props = {} } = component;
    
    // 生成基础HTML
    const html = `<div id="${id}" class="exported-component" style="${this.generateStyleString(style)}">
  <!-- 组件内容占位符 -->
</div>`;
    
    return {
      html,
      js: '',
      resources: []
    };
  }
  
  /**
   * 辅助函数：样式对象转字符串
   * @param {Object} style 样式对象
   * @returns {string} 样式字符串
   */
  generateStyleString(style = {}) {
    return Object.entries(style)
      .map(([key, value]) => `${key}: ${value};`)
      .join(' ');
  }
  
  /**
   * 导出整个组件树
   * @param {Array} components 组件树
   * @param {Object} options 导出选项
   * @returns {Promise<Object>} 导出结果
   */
  async exportComponentTree(components, options = {}) {
    if (!Array.isArray(components) || components.length === 0) {
      return { html: '', js: '', resources: [] };
    }
    
    let html = '';
    let js = '';
    const resources = [];
    const processedResources = new Set(); // 用于去重
    
    // 处理每个组件
    for (const component of components) {
      const result = await this.exportComponent(component, options);
      
      html += result.html + '\n';
      js += result.js ? result.js + '\n' : '';
      
      // 添加并去重资源
      if (result.resources && result.resources.length > 0) {
        for (const resource of result.resources) {
          const resourceKey = `${resource.type}:${resource.path}`;
          if (!processedResources.has(resourceKey)) {
            resources.push(resource);
            processedResources.add(resourceKey);
          }
        }
      }
      
      // 处理子组件
      if (component.children && component.children.length > 0) {
        const childResult = await this.exportComponentTree(component.children, options);
        
        // 在父组件的html中插入子组件内容
        html = html.replace('<!-- 组件内容占位符 -->', childResult.html);
        js += childResult.js ? childResult.js + '\n' : '';
        
        // 添加并去重子组件资源
        for (const resource of childResult.resources) {
          const resourceKey = `${resource.type}:${resource.path}`;
          if (!processedResources.has(resourceKey)) {
            resources.push(resource);
            processedResources.add(resourceKey);
          }
        }
      }
    }
    
    return { html, js, resources };
  }
  
  /**
   * 生成完整的HTML文档
   * @param {Object} exportData 导出数据
   * @param {Object} options 选项
   * @returns {string} 完整HTML文档
   */
  generateFullHtml(exportData, options = {}) {
    const { html, js, resources } = exportData;
    const { title = '导出项目', width = 800, height = 600 } = options;
    
    // 构建资源链接
    const resourceLinks = resources.map(res => {
      if (res.type === 'css') {
        return `<link rel="stylesheet" href="${res.path}">`;
      } else if (res.type === 'js') {
        return `<script src="${res.path}"></script>`;
      }
      return '';
    }).join('\n  ');
    
    return `<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${title}</title>
  ${resourceLinks}
  <style>
    /* 基础样式 */
    body {
      margin: 0;
      padding: 0;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
    }
    .exported-container {
      position: relative;
      width: ${width}px;
      height: ${height}px;
      margin: 0 auto;
      overflow: hidden;
      border: 1px solid #ddd;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }
    .exported-component {
      position: absolute;
    }
  </style>
</head>
<body>
  <div class="exported-container">
    ${html}
  </div>
  
  <script>
  // 组件交互逻辑
  ${js}
  </script>
</body>
</html>`;
  }
  
  /**
   * 导出为Miniblink格式
   * @param {Array} components 组件树
   * @param {Object} options 选项
   * @returns {Promise<Object>} 导出结果
   */
  async exportForMiniblink(components, options = {}) {
    // 确保组件类型正确处理
    const processedComponents = components.map(comp => {
      // 处理自定义组件类型，如ew-button转为button
      const modifiedComp = {...comp};
      
      // 处理组件类型转换
      if (modifiedComp.type && modifiedComp.type.startsWith('ew-')) {
        modifiedComp.type = modifiedComp.type.replace('ew-', 'el-');
      }
      
      // 处理props.datas对象，确保导出时能正确使用
      if (modifiedComp.props && modifiedComp.props.datas && typeof modifiedComp.props.datas === 'object') {
        // 将datas中的属性直接添加到props中
        Object.keys(modifiedComp.props.datas).forEach(key => {
          // 不覆盖已有的同名属性
          if (modifiedComp.props[key] === undefined) {
            modifiedComp.props[key] = modifiedComp.props.datas[key];
          }
        });
      }
      
      return modifiedComp;
    });
    
    // 处理组件树
    const exportData = await this.exportComponentTree(processedComponents, {
      ...options,
      mode: 'miniblink'
    });
    
    // 生成完整HTML
    const html = this.generateFullHtml(exportData, {
      ...options,
      title: options.title || 'Miniblink UI',
    });
    
    return {
      html,
      success: true,
      message: '导出成功'
    };
  }
}

// 创建单例实例
const exportService = new ExportService();

export default exportService; 